<script setup lang="ts">
  import { useI18n } from 'vue-i18n';
  import { computed, nextTick, reactive, ref } from 'vue';
  import {
    Message,
    PaginationProps,
    TableColumnData,
  } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { deleteRoleById, selectPageRole } from '@/api/role';
  import AddModal from '@/views/system/role/components/add-modal.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const roleStatusFieldNames = { value: 'value', label: 'label' };
  const roleStatusOptions = ref([
    {
      label: '全部',
      value: -1,
    },
    {
      label: '启用',
      value: 1,
    },
    {
      label: '禁用',
      value: 0,
    },
  ]);
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event,
  ) => {
    size.value = val as SizeProps;
  };
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);
  // 角色信息列表
  const columns: TableColumnData[] = [
    {
      title: '角色名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '编码',
      dataIndex: 'code',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'enable',
      align: 'center',
      slotName: 'enable',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      slotName: 'operation',
      width: 250,
    },
  ];
  const roleList = ref([]);
  const params = ref({
    pageNo: 1,
    pageSize: 10,
    name: '',
    enable: -1,
  });
  const pagination = reactive<PaginationProps>({
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [5, 10, 50, 100],
  });
  const getRoleList = async () => {
    setLoading(true);
    try {
      const result = await selectPageRole(params.value);
      roleList.value = result.data.list;
      pagination.total = result.data.total;
      pagination.current = params.value.pageNo;
      pagination.pageSize = params.value.pageSize;
    } finally {
      setLoading(false);
    }
  };
  getRoleList();
  // 查询
  const handleSearch = () => {
    params.value.pageNo = 1;
    getRoleList();
  };
  // 重置
  const handleReset = () => {
    params.value.pageNo = 1;
    params.value.name = '';
    params.value.enable = -1;
    getRoleList();
  };
  // 刷新
  const handleReFresh = () => {
    getRoleList();
  };
  // 切换页面
  const handlePageNoChange = (pageNo: number) => {
    params.value.pageNo = pageNo;
    getRoleList();
  };
  // 变更页数数量
  const handlePageSizeChange = (pageSize: number) => {
    params.value.pageSize = pageSize;
    getRoleList();
  };
  // 删除
  const handleDelete = async (id: number) => {
    await deleteRoleById(id);
    Message.success('删除成功');
    // 重新查询
    if (roleList.value.length === 1 && params.value.pageNo !== 1) {
      params.value.pageNo -= 1;
    }
    await getRoleList();
  };
  const addModalRef = ref();
  const handleOpen = () => {
    addModalRef.value?.handleOpen();
  };
  const handleEdit = (id: number) => {
    addModalRef.value?.handleEdit(id);
  };
  // 保存成功回调函数
  const handleSaveSuccess = () => {
    getRoleList();
  };
</script>

<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="name" label="角色名：" label-col-flex="70px">
          <a-input v-model="params.name" placeholder="请输入角色名" />
        </a-form-item>
        <a-form-item field="status" label="状态：" label-col-flex="70px">
          <a-select
            v-model="params.enable"
            :options="roleStatusOptions"
            :field-names="roleStatusFieldNames"
            placeholder="请选择角色状态"
            :style="{ width: '180px' }"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'system:role:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button
          v-permission="'system:role:add'"
          type="primary"
          @click="handleOpen"
        >
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('searchTable.operation.create') }}
        </a-button>
      </a-space>
    </a-col>
    <a-col
      :span="12"
      style="display: flex; align-items: center; justify-content: end"
    >
      <a-space :size="12">
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          {{ $t('searchTable.operation.download') }}
        </a-button>
        <a-tooltip
          :content="$t('searchTable.actions.refresh')"
          @click="handleReFresh"
        >
          <div class="action-icon">
            <icon-refresh size="18" />
          </div>
        </a-tooltip>
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('searchTable.actions.density')">
            <div class="action-icon">
              <icon-line-height size="18" />
            </div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
      </a-space>
    </a-col>
  </a-row>
  <a-row style="flex: 1">
    <a-col :span="24">
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="roleList"
        :scroll="{ y: 'calc(100vh - 311px)' }"
        :bordered="false"
        :size="size"
        :pagination="pagination"
        page-position="br"
        @page-change="handlePageNoChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #enable="{ record }">
          <a-tag :color="record.enable === 1 ? 'green' : 'red'">
            {{ record.enable === 1 ? '启用' : '关闭' }}
          </a-tag>
        </template>
        <template #operation="{ record }">
          <a-button
            v-permission="'system:role:edit'"
            type="text"
            @click="handleEdit(record.id)"
            >{{ $t('searchTable.operation.edit') }}
          </a-button>
          <a-popconfirm
            :content="$t('modal.operation.tips')"
            @ok="handleDelete(record.id)"
          >
            <a-button v-permission="'system:role:remove'" type="text"
              >{{ $t('searchTable.operation.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-col>
  </a-row>
  <add-modal ref="addModalRef" @save-success="handleSaveSuccess"></add-modal>
</template>

<style scoped lang="less">
  .action-icon {
    cursor: pointer;
  }
</style>
